#include "sql.h"

#include <QDebug>
#include<QCryptographicHash>
#include<QSqlQuery>
#include<QSqlError>
#include<QDebug>
#include<QDate>
#include"denglu.h"
#include"zhuce.h"
#include"wangjimima.h"
#include"yanzhengdenglu.h"
SqlController*SqlController::s_instasnce = nullptr;

SqlController::SqlController(){

}
SqlController * SqlController::getInstance(){
    if(s_instasnce == nullptr){
        s_instasnce = new SqlController();
    }
    return s_instasnce;
}

//建立链接
bool SqlController::initDataBase(){
    qDebug()<<"DB drivers:"<<QSqlDatabase::drivers();
    m_db = QSqlDatabase::addDatabase(DB_DRIVE);
    m_db.setHostName(DB_HOST_NAME);
    m_db.setPort(DB_PORT);
    m_db.setUserName(DB_USER_NAME);
    m_db.setPassword(DB_PASSWORD);
    m_db.setDatabaseName(DB_DATABASE_NAME);

    if(m_db.open()){
        qDebug()<<"success";
        return true;
    }
    qDebug()<<"connect failed";
    return false;
}
//创建表
bool SqlController::createUserTable(QString SQL_TABLE) {
    QSqlQuery query(m_db);
    if (!query.exec(SQL_TABLE)) {
        qDebug() << "Error creating user table:" << query.lastError().text();
        return false;
    }

    qDebug() << "User table created successfully";
    return true;
}
//注册
bool SqlController::registerUser(const QString &username, const QString &password, const QString &email)
{
    qDebug()<<username;
    qDebug()<<password;
    qDebug()<<email;
    QString mdPassword = strToMd5(password);
    qDebug()<<mdPassword;
    QString insertUserSQL = "INSERT INTO UserInfo (name, password, email, auth) "
                            "VALUES (:name, :password, :email, :auth)";

    QSqlQuery query;
    query.prepare(insertUserSQL);
    query.bindValue(":name", username);
    query.bindValue(":password", mdPassword);
    query.bindValue(":email", email);
    query.bindValue(":auth", 1); // 权限

    if (!query.exec()) {
        qDebug() << "Error registering user:" << query.lastError().text();
        return false;
    }

    qDebug() << "用户注册成功";
    return true;
}

//登录
bool SqlController::goLogin(QString name,QString pwd){
    QString mdPassword = strToMd5(pwd);
    QString strLoging = "SELECT * FROM userinfo WHERE NAME = ?";
    QSqlQuery loginQuery;
    loginQuery.prepare(strLoging);
    loginQuery.addBindValue(name);
    if(loginQuery.exec()){
        while (loginQuery.next()) {
            QString  strPwd = loginQuery.value("password").toString();
            if(strPwd == mdPassword){
                return true;
            }
        }
    }
    return false;
}

//用户管理
//保存登录信息
bool SqlController::getUsername(QString name, UserLogin &user){
    QString queryStr = "SELECT id, name, auth FROM userinfo WHERE name = ?";
       QSqlQuery query;
       query.prepare(queryStr);
       query.addBindValue(name);

       if (query.exec()) {
           if (query.next()) {
               user.id = query.value("id").toInt();
               user.name = query.value("name").toString();
               user.auth = query.value("auth").toInt();
    return true;
           }
       } else {
           qDebug() << "Error executing user info query:" << query.lastError().text();
       }
       return false;
}



//用户管理
QList<UserChange> SqlController::getUserData()
{
    QList<UserChange> userData;
    QSqlQuery query("SELECT id, name, auth, email FROM UserInfo");
    while (query.next()) {
        UserChange data;
        data.id = query.value(0).toInt();
        data.name = query.value(1).toString();
        data.auth = query.value(2).toInt();
        data.email = query.value(3).toString();
        userData.append(data);
    }
    return userData;
}

bool SqlController::updateUser(int id, const QString &name, int auth, const QString &email)
{   qDebug()<<id;
    qDebug()<<name;
    qDebug()<<auth;
    qDebug()<<email;
    QSqlQuery query;
    query.prepare("UPDATE UserInfo SET auth = :auth, email = :email WHERE id = :id");
    query.bindValue(":auth", auth);
    query.bindValue(":email", email);
    query.bindValue(":id", id);

    if (!query.exec()) {
        qWarning() << "Update error: " << query.lastError().text();
        return false;
    }
    return true;
}

//重置密码
bool SqlController::resetPassword(QString& newPassword) {
        QSqlDatabase db = QSqlDatabase::database(); // 获取数据库连接

        if (!db.isOpen()) {
            qDebug() << "Database is not open.";
            return false;
        }

        QSqlQuery query(db);
        query.prepare("UPDATE users SET password = :newPassword");
        query.bindValue(":newPassword", newPassword);


        if (query.exec()) {
            qDebug() << "密码重置成功.";
            return true;
        } else {
            qDebug() << "密码重置失败:" << query.lastError().text();
            return false;
        }
    }
